package org.misty.practices.jedis;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.List;

public class JedisClusterFactory {
  private JedisCluster jedisCluster;

  private List<String> hostPortList;

  /**
   * ms
   */
  private int timeout = 30000;

  synchronized private void init() {
    if (jedisCluster != null) {
      return;
    }

    var poolConfig = new JedisPoolConfig();

    var nodeSet = new HashSet<HostAndPort>();
    for (var s : hostPortList) {
      var arr = s.split(":");
      if (arr.length != 2) {
        continue;
      }
      nodeSet.add(new HostAndPort(arr[0], Integer.parseInt(arr[1])));
    }

    try {
      jedisCluster = new JedisCluster(nodeSet, timeout, poolConfig);
    } catch (Exception ex) {
      // 打印日志
      ex.printStackTrace();
    }
  }

  synchronized public void destroy() {
    if (jedisCluster != null) {
      try {
        jedisCluster.close();
      } catch (Exception e) {
        e.printStackTrace();
      }

      jedisCluster = null;
    }
  }


  public void setHostPortList(List<String> hostPortList) {
    this.hostPortList = hostPortList;
  }

  public void setTimeout(int timeout) {
    this.timeout = timeout;
  }
}
